from module.bi_ji import bi_ji
from flask import request, render_template, redirect, session, url_for, jsonify
import os
from module.bi_ji.sqldb import check_username_and_password, save_username_and_password
import shutil

@bi_ji.route("/")
def index():
    if "username" not in session:
        return redirect(url_for("bi_ji.login"))
    base_path=".\\data\\bi_ji\\"+session["username"]+"\\"
    if not os.path.exists(base_path):
        os.makedirs(base_path)
    session["cur_path"]=base_path
    return render_template("/bi_ji/index.html")


@bi_ji.route("/login", methods=["POST", "GET"])
def login():
    print(request.method)
    if request.method == "POST":
        username = request.form.get("username")
        password = request.form.get("password")
        if check_username_and_password(username, password):
            session["username"] = username
            return jsonify({"login": True})
        else:
            return jsonify({"login": False})
    return render_template("/bi_ji/login.html")


@bi_ji.route("/sigin_up", methods=["POST"])
def sigin_up():
    username = request.form.get("username")
    password = request.form.get("password")
    if username is None or password is None:
        return jsonify({"sigin_up": False, "msg": "账户密码不符合规定，请重新注册"})
    if save_username_and_password(username, password):
        return jsonify({"sigin_up": True, "msg": "账号注册成功！"})
    else:
        return jsonify({"sigin_up": True, "msg": "账户已存在，请不要重复注册！"})


@bi_ji.route("/save", methods=["GET", "POST"])
def save():
    title = request.form.get("title")
    comment = request.form.get("content")
    with open(session["cur_path"]+"\\"+title,"w",encoding="utf-8") as f:
        f.write(comment)
    return redirect(url_for("bi_ji.index"))

@bi_ji.route("/get_md/<file_name>")
def get_md(file_name):
    with open(session["cur_path"]+"\\"+file_name,"r",encoding="utf-8") as f:
        md_text =f.read()
        return render_template("/bi_ji/markdown.html",md_tilte=file_name,md_text=md_text)

@bi_ji.route("/get_path")
def get_path():
    """
    获取当前用户的目录
    """
    arg1=request.args.get("get_path")
    # 路径过滤和判断
    if arg1 == "..\\":
        arg1=获取父路径(session["cur_path"])
    elif arg1==".\\":
        arg1=".\\data\\bi_ji\\"+session["username"]+"\\"
    if not os.path.isdir(arg1):
        return jsonify({"jie_g":False,"msg":"路径无效"})

    # 获取目录
    root,dirs,files=next(os.walk(arg1))
    if not root[-1]=="\\":
        root+="\\"
    session["cur_path"]=root
    return jsonify({"jie_g":True,"root":root,"dirs":dirs,"files":files})
        
@bi_ji.route("/del")
def del_file():
    arg1=request.args.get("del_file")
    if os.path.isdir(arg1):
        shutil.rmtree(arg1)
        return jsonify({"jie_g":True})
    if os.path.isfile(arg1):
        os.remove(arg1)
        return jsonify({"jie_g":True})
    return jsonify({"jie_g":False,"msg":"错误"})

def 获取父路径(path1:str):
    list1=path1.split('\\')
    # 判断是否到了根节点,是就返回无效节点
    if len(list1)<=5:
        return ""
    list2=list1[:-2]
    父路径=""
    for i in list2:
        父路径+=(i+'\\')
    return 父路径

@bi_ji.route("/upload_img",methods=["GET", "POST"])
def upload_img():
    # print(request.get_data())
    img_id=request.args.get("guid")
    print(img_id)
    return jsonify({"success":1,"message":"1","url":"http://127.0.0.1:5000/static/man_hua/1.jpg"})